package com.app.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.app.constant.Constant;
import com.app.dataprovider.DataProvider;
import com.app.model.Word;

@SuppressWarnings("serial")
public class MainServlet extends HttpServlet {
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("application/json");
		
		PrintWriter out = resp.getWriter();
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("server-time", Calendar.getInstance().getTimeInMillis());

		String cmd = req.getParameter("cmd");
		if (cmd == null) {
		} else if (cmd.equals("get_default_book")) {
			JSONArray jsonArray = getDefaultBook();
			jsonObj.put("result", jsonArray);
		} else if (cmd.equals("get_book")) {
			jsonObj.put("result", "OK");
		} else if (cmd.equals("add_word")) {
			doAddNewWord(req);
			jsonObj.put("result", "OK");
		} else if (cmd.equals("add_book")) {
			jsonObj.put("result", "OK");
		} else if (cmd.equals("clear_default_book")) {
			clearDefaultBook();
			jsonObj.put("result", "OK");
		} else if (cmd.equals("delete_word")) {
			doDeleteWord(req);
			jsonObj.put("result", "OK");
		}
		
		out.println(jsonObj.toJSONString());
		out.flush();
	}
	
	private void clearDefaultBook() {
		DataProvider.getInstance().getBookSet(Constant.BOOK_DEFAULT).clear();
	}
	
	private void doDeleteWord(HttpServletRequest req) {
		String longId = req.getParameter("id");
		if (longId == null || longId.isEmpty()) {
			return;
		}
		try {
			long id = Long.parseLong(longId);
			DataProvider.getInstance().deleteWord(Constant.BOOK_DEFAULT, id);
		} catch (Exception e) {
		}
	}
	
	private void doAddNewWord(HttpServletRequest req) {
		String word = req.getParameter("word");
		String description = req.getParameter("desc");
		String imagePath = req.getParameter("imgPath");
		
		if (word == null || word.isEmpty()) {
			System.out.println("Can not add an empty word");
			return;
		}
		
		Word w = new Word();
		w.setWord(word);
		w.setDescription(description);
		w.setImagePath(imagePath);
		
		DataProvider.getInstance().addWord(Constant.BOOK_DEFAULT, w, true);
	}
	
	private JSONArray getDefaultBook() {
		return gettBook(Constant.BOOK_DEFAULT);
	}
	
	@SuppressWarnings("unchecked")
	private JSONArray gettBook(String name) {
		List<Word> lstWord = DataProvider.getInstance().getBookSet(name);
		
		JSONArray jsonArr = new JSONArray();
		for (Word w : lstWord) {
			JSONObject json = new JSONObject();
			jsonArr.add(json);
			
			json.put("id", w.getId());
			json.put("word", w.getWord());
			json.put("description", w.getDescription());
			json.put("imagePath", w.getImagePath());
		}
		
		return jsonArr;
	}
}
